#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cexapi
import datetime
import re
from dateutil import parser
import calendar
from os import listdir
from os.path import isfile, join

import glob
import platform
import ast
import sys
import tablePrint

out = sys.stdout
formattab = tablePrint.tableprint()



def getDataFromLog(logfileName):
     
    if platform.system()=="Windows":
        fileSep="\\"        
        mypath="C:"+fileSep+"Daten"+fileSep+"workspace"+fileSep+"PyTest"+fileSep+"trade"
    
    if platform.system()=="Linux":
        fileSep="/"    
        mypath="." 
        
    
                
    logFile = mypath+fileSep+logfileName
    selLogFile = mypath+fileSep+"Kop"+logfileName
    
    retVal=[0,0,0]
    
    transactionsFile = open(logFile, 'r+')
    selectedtransactionsFile = open(selLogFile, 'a+')
     
    lineCount=0    
    rateSum=0 
    maxRate=-1
    minRate=1000 
    for line in transactionsFile:
        splitLine = re.split(';', line)
        datumZeitStr=re.split(',',splitLine[0])[0] 
        datumZeit = parser.parse(datumZeitStr)
        datumZeitUTSec=calendar.timegm(datumZeit.utctimetuple())
        
        arrStr=splitLine[1].strip()
        dataArr=ast.literal_eval(arrStr)
        now = datetime.datetime.now()
        
        if now<datumZeit+datetime.timedelta(hours = 1):  
            #print datumZeitStr  
            #print dataArr
            rateSum += float(dataArr[1][2])
            lineCount += 1
            if maxRate<float(dataArr[1][2]):
                maxRate=float(dataArr[1][2])
                maxRateTime=datumZeitStr
            if minRate>float(dataArr[1][2]):
                minRate=float(dataArr[1][2])
                minRateTime=datumZeitStr
            #formattab.pprint_table(out,dataArr)   
            #selectedtransactionsFile.write(line)
            
    print "medRate=",rateSum/lineCount
    print "maxRate=",maxRate, "@",maxRateTime
    print "minRate=",minRate, "@",minRateTime
        
            
    selectedtransactionsFile.close()
    transactionsFile.close()
            
   
    return retVal

try:
    getDataFromLog("Kopsellatlimit.log")
except:
    print "generalException"
    raise
    

